﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using System.IO;
using System.Xml.Schema;
using System.Xml;
using MyAlbum.Logging;

namespace PersonalAlbum
{
    public class Lang : ILanguageService
    {
        private const string SessionLangKey = "lang";
        private const string SessionDirectionKey = "direction";
        public const string ApplicationLangKey = "defaultLang";
        public const string ApplicationDirectionkey = "defaultDirection";
        public string TextDirection
        {
            get
            {   
                if (HttpContext.Current.Session[SessionDirectionKey] != null)
                {
                    return HttpContext.Current.Session[SessionDirectionKey] as string;
                }
                else
                {
                    return HttpContext.Current.Application[ApplicationDirectionkey] as string;
                }
            }

        }

        public string Language
        {
            get
            {
                if (HttpContext.Current.Session != null &&
                    HttpContext.Current.Session[SessionLangKey] != null)
                {
                    return HttpContext.Current.Session[SessionLangKey] as string;
                }
                else
                {
                    return HttpContext.Current.Application[ApplicationLangKey] as string;
                }
            }
            set
            {
                if (value == null)
                {
                    throw new ArgumentNullException("value");
                }
                HttpContext.Current.Session[SessionLangKey] = value;

                if (value.Equals("hebrew", StringComparison.InvariantCultureIgnoreCase) ||
                    value.Equals("arabic", StringComparison.InvariantCultureIgnoreCase))
                {
                    HttpContext.Current.Session[SessionDirectionKey] = "rtl";
                }
                else
                {
                    HttpContext.Current.Session[SessionDirectionKey] = "ltr";
                }
               
            }
        }

        public void SetDefaultLanaguage(string lang)
        {
            HttpContext.Current.Application[ApplicationLangKey] = lang;
            if (lang.Equals("hebrew", StringComparison.InvariantCultureIgnoreCase) ||
           lang.Equals("arabic", StringComparison.InvariantCultureIgnoreCase))
            {
                HttpContext.Current.Application[ApplicationDirectionkey] = "rtl";
            }
            else
            {
                HttpContext.Current.Application[ApplicationDirectionkey] = "ltr";
            }
        }

        public string GetText(string label)
        {
            //XmlSchemaInference infer = new XmlSchemaInference();
            //XmlSchemaSet schemaSet =
            //infer.InferSchema(new XmlTextReader( Path.Combine(HttpContext.Current.Server.MapPath("~"), @"Lang\Hebrew\labels.xml")));
            //XmlWriter w = XmlWriter.Create(Path.Combine(HttpContext.Current.Server.MapPath("~"), @"Lang\labels.xsd"));
            //foreach (XmlSchema schema in schemaSet.Schemas())
            //{
            //    schema.Write(w);
            //}
            //w.Close();
            try
            {
                string lang = this.Language;
                if (HttpContext.Current.Cache[lang] == null)
                {
                    FillLabels(lang);
                }
                Dictionary<string, string> d = HttpContext.Current.Cache[lang] as Dictionary<string, string>;
                if (d.ContainsKey(label))
                {
                    return d[label];
                }
                else
                {
                    WebLogger.Warning( "missing label:" + label);
                    return "missing label :" + label;

                }
            }
            catch (Exception e1)
            {
               WebLogger.LogError(e1, "label:" + label);
                return label;
            }
        }

        private void FillLabels(string lang)
        {
            XDocument doc = XDocument.Parse(
                File.ReadAllText(
                Path.Combine(HttpContext.Current.Server.MapPath("~"), @"Lang\" + lang + @"\labels.xml")));
            Dictionary<string, string> dic = new Dictionary<string, string>();
            var labels = from s in doc.Descendants("Label") select new { Key = s.Attribute("key").Value, Value = s.Value.Trim() };
            foreach (var item in labels)
            {
                try
                {
                    dic.Add(item.Key, item.Value);
                }
                catch (Exception e1)
                {
                  WebLogger.LogError(e1, "item key:" + item.Key);
                }
            }
            lock (HttpContext.Current.Cache)
            {
                if (HttpContext.Current.Cache[lang] == null)
                {
                    HttpContext.Current.Cache.Add(lang, dic, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromDays(7), System.Web.Caching.CacheItemPriority.Normal, null);
                }
            }
        }
    }
}
